package com.sendtion.xrichtextdemo.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * StringUtils
 *
 * @since 2021-06-22
 */
public class StringUtils {
    /**
     * REPLACERELE
     */
    public static final String REPLACERELE = "&@!";
    private static final int INT_2 = 2;
    private static final int INT_3 = 3;
    /**
     * cutStringByImgTag
     *
     * @param targetStr 要处理的字符串
     * @return List
     * @description 切割字符串，将文本和img标签碎片化，如"ab<img>cd"转换为"ab"、"<img>"、"cd"
     */

    public static List<String> cutStringByImgTag(String targetStr) {
        List<String> splitTextList = new ArrayList<String>();
        Pattern pattern = Pattern.compile("<img.*?src=\\\"(.*?)\\\".*?>");
        Matcher matcher = pattern.matcher(targetStr);
        int lastIndex = 0;
        while (matcher.find()) {
            if (matcher.start() > lastIndex) {
                splitTextList.add(targetStr.substring(lastIndex, matcher.start()));
            }
            splitTextList.add(targetStr.substring(matcher.start(), matcher.end()));
            lastIndex = matcher.end();
        }
        if (lastIndex != targetStr.length()) {
            splitTextList.add(targetStr.substring(lastIndex, targetStr.length()));
        }
        return splitTextList;
    }

    /**
     * 获取img标签中的src值
     *
     * @param content
     * @return String
     */
    public static String getImgSrc(String content) {
        String strsrc = null;
        Pattern pimg = Pattern.compile("<(img|IMG)(.*?)(/>|></img>|>)");
        Matcher mimg = pimg.matcher(content);
        boolean isResultimg = mimg.find();
        if (isResultimg) {
            while (isResultimg) {
                String strimg = mimg.group(INT_2);
                Pattern psrc = Pattern.compile("(src|SRC)=(\"|\')(.*?)(\"|\')");
                Matcher msrc = psrc.matcher(strimg);
                if (msrc.find()) {
                    strsrc = msrc.group(INT_3);
                }
                isResultimg = mimg.find();
            }
        }
        return strsrc;
    }

    /**
     * 从html文本中提取图片地址，或者文本内容
     *
     * @param html 传入html文本
     * @param isGetImage true获取图片，false获取文本
     * @return ArrayList
     */
    public static ArrayList<String> getTextFromHtml(String html, boolean isGetImage) {
        ArrayList<String> imageList = new ArrayList<>();
        ArrayList<String> textList = new ArrayList<>();
        List<String> list = cutStringByImgTag(html);
        for (int i = 0; i < list.size(); i++) {
            String text = list.get(i);
            if (text.contains("<img") && text.contains("src=")) {
                String imagePath = getImgSrc(text);
                imageList.add(imagePath);
            } else {
                textList.add(text);
            }
        }
        if (isGetImage) {
            return imageList;
        } else {
            return textList;
        }
    }
}
